<?php

namespace App\Repository\CatchConf;

use App\Models\CatchConf\PddCatchModel as model;
use Illuminate\Support\Facades\Cache;
use App\Repository\RoleRepository;
use Illuminate\Support\Facades\DB;
use App\Repository\BaseRepository;
use App\Repository\Product\ProductRepository;
use App\Libs\PhpOffice\Excel;
use App\Models\Order\OrderExportModel;

class PddCatchRepository extends  BaseRepository
{
    private $model;
    private $productModel;
    public function __construct()
    {
        $this->model = new model();
        $this->productModel = new ProductRepository();
        parent::__construct();
    }
    //列表
    public function index($where)
    {
        $cron = $where;
        $cron['order'] = ['orderby' => 'id', 'orderdir' => 'desc'];
        $data = $this->search($this->model, $cron);
        if (!empty($data['data'])) {
            foreach ($data['data'] as $key => &$v) {
                if (!empty($v['remarks'])) {

                    $v['remarks'] = html_entity_decode($v['remarks']);
                }
                if(empty(env('IS_ENCRYP')) || env('IS_ENCRYP') != 2){
                    if(mb_strlen($v['name']) <= 2){
                      $v['name'] = str_replace(mb_substr($v['name'],-1,mb_strlen($v['name'])-1),'***',($v['name']));
                    }else{
                      $v['name'] = str_replace(mb_substr($v['name'],-2,mb_strlen($v['name'])-1),'***',($v['name']));
                    }
                    
                    $v['identity'] = str_replace(mb_substr($v['identity'],3,11),'*******',($v['identity']));
                    $v['contact'] = str_replace(mb_substr($v['contact'],3,4),'***',($v['contact']));
                    $v['address'] = str_replace(mb_substr($v['address'],4,mb_strlen($v['address'])-4),'***',($v['address']));
                }
            }
            
        }
        return $data;
    }
    //添加
    public function add($data)
    {
        //必填 字段
        $mustField = [
            'dist_orderno',
        ];
        $optionalFields = $this->model->getTableField();
        $msgField = [
            'dist_orderno' => '订单id不能为空',
        ];
        $insertData  = $this->getRealData($data, $mustField, $optionalFields, $msgField);
        if (!empty($insertData) && is_string($insertData)) {
            //返回错误参数
            return $this->returnMsg(
                2,
                $insertData
            );
        }
        if (isset($insertData['status'])) {
            $insertData['status_desc'] = $this->model->getOrderStatusDesc($insertData['status']);
        }
        if (empty($insertData['created_at'])) {
            $insertData['created_at'] = date('Y-m-d H:i:s');
        }

        $insertData['shop_id'] = (!empty($data['shop_id']) ? $data['shop_id'] : (!empty($data->user->shop_id) ? $data->user->shop_id : ''));

        $res = $this->model->insert($insertData);
        if ($res) {
            return $this->returnMsg(200, '上传成功', ['id' => $insertData['dist_orderno']]);
        }
        return $this->returnMsg(1, '上传失败');
    }
    //删除
    public function del($where)
    {
        $flag = true;
        $msg = '未知错误';
        $code = 1;
        if (empty($where)) {
            $flag = false;
            $msg = '删除条件不能为空';
            $code = 2;
        }
        if ($flag) {
            $res = $this->model->where($where)->get();
            if (!$res) {
                $flag = false;
                $msg = '未查询到数据';
                $code = 3;
            }
        }
        if ($flag) {
            $del = $this->model->where($where)->delete();
            if ($del) {
                $msg = '删除成功';
                $code = 200;
            }
        }
        return $this->returnMsg($code, $msg);
    }
    //修改
    public function edit($where, $data, $isMust = false)
    {
        if (empty($where)) {
            return $this->returnMsg(1, '条件不能为空');
        }
        if (empty($data)) {
            return $this->returnMsg(2, '修改参数不能为空');
        }
        //过滤字段
        //过滤字段
        $optionalFields = $this->model->getTableField();
        $field  = $this->getRealData($data, [], $optionalFields, []);
        if (isset($field['status'])) {
            $field['status_desc'] = $this->model->getOrderStatusDesc($field['status']);;
        }
        //先查询是否存在
        $res = $this->model->where($where)->update($field);
        if ($isMust && $res) {
            return $this->returnMsg(200, '修改成功');
        }
        if (!$isMust) {
            return $this->returnMsg(200, '修改成功');
        }
        return $this->returnMsg(3, '请重新修改');
    }
    //列表查询
    public function lists($where = [], $page = 1, $limit = 10)
    {
        $res = $this->search($this->model, $where, $page, $limit);

        return $res;
    }
    public function getOne($where, $field = ['*'])
    {
        return $this->model->where($where)->select($field)->first();
    }
    public function getOrderStatus()
    {
        $res = $this->model->orderStatus();
        $return = [];
        foreach ($res as $key => $v) {
            $return[] = [
                'id' => $key,
                'value' => $v
            ];
        }
        return $return;
    }
    //导出订单
    public function getExcelPort($id, $params, $name, $shop_id = 0)
    {
        if (!empty($params)) {
            $request = json_decode($params, true);
            $where['where']['shop_id'] = $shop_id;
            if (!empty($request['status'])) {
                $where['where']['status'] = $request['status'];
            }
            if (!empty($request['dist_orderno'])) {
                $where['where']['dist_orderno'] = trim($request['dist_orderno'], ' ');
            }
            if (!empty($request['identity'])) {
                $where['where']['identity'] = trim($request['identity'], ' ');
            }
            if (!empty($request['iccid'])) {
                $where['where']['iccid'] = $request['iccid'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['express_number'])) {
                $where['where']['express_number'] = $request['express_number'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            if (!empty($request['contact'])) {
                $where['where']['contact'] = $request['contact'];
                // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            }
            // if (!empty($request['name'])) {
            //     $where['where']['name'] = $request['name'];
            //     // $where['where'] = ['sup_orderno' => $request->get('sup_orderno')];
            // }
            if (!empty($request['douyin_name'])) {
                $where['where']['douyin_name'] = $request['douyin_name'];
            }
            if (!empty($request['number'])) {
                $where['like']['name'] = $request['number'];
            }
            //时间验证 
            if (!empty($request['dateRange'])) {
                // $time = $request->get('dateRange');
                $where['between'] = ['created_at' => $request['dateRange']];
            }
            if (!empty($request['params'])) {
                // $time = $request->get('dateRange');
                $where['between'] = ['created_at' => [$request['params']['beginTime'], $request['params']['endTime']]];
            }
        }
        $where['limit']['start'] = 0;
        $where['limit']['number'] = 50000;
        // var_dump($where);
        $resData = $this->index($where);
        // var_dump($resData);
        $model = new Excel();
        $title = [
            '订单编号',
            '商品编号',
            '用户姓名',
            '用户联系电话',
            '证件信息',
            '省',
            '市',
            '区',
            '详细地址',
            '订单状态',
            '提交失败信息',
            '分销员',
            '达人id',
            '达人昵称',
            '备注',
            '提交时间',
            '店铺名称'
        ];
        $excelData = [];
        foreach ($resData['data'] as $key => $v) {
            if(empty(env('IS_ENCRYP')) || env('IS_ENCRYP') != 2){
                if(!empty($v['identity'])){
                  $v['identity'] = str_replace(mb_substr($v['identity'],3,11),'***',($v['identity']));
                }
              }
            $excelData[] = [
                $v['dist_orderno'],
                $v['goods_code'],
                $v['name'],
                $v['contact'],
                $v['identity'] . ' ',
                $v['province'],
                $v['city'],
                $v['area'],
                $v['address'],
                $v['status_desc'],
                $v['three_msg'],
                $v['douyin_name'],
                $v['author_id'],
                $v['author_name'],
                $v['remark'],
                $v['created_at'],
                $v['dist_name']
            ];
        }
        $fielname = '/attach/excel/' . $name . date('YmdHis') . '.xlsx';
        $model->exportFile($excelData, $title, $fielname);
        $excelModel = new OrderExportModel();
        $excelModel->where(['id' => $id])->update(['is_run' => 1, 'path' => $fielname]);
        return $this->returnMsg(200, '导出成功', ['fiel' => $fielname]);
    }
}
